package com.cloudcc.mobile.view.web;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.view.dynamic.RelevantActivtiy;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.litesuits.android.log.Log;

public class NewWebView extends Activity {

    private String mEns = RunTimeManager.getInstance().getlanguage();
    private WebView webview;
    protected String mUrl = StringUtils.EMPTY;
    // Context mContext;
    private boolean _isVisible;// 控制bindtoken影响的问题
    protected CallLogLoadingDialog mProgress;
    public String newurl;
    public static NewWebView instance = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newworkwebview);
        instance = this;
        mProgress = new CallLogLoadingDialog(this, R.style.DialogLoadingTheme);
        webview = (WebView) findViewById(R.id.newworkweb);
        webview.requestFocus();
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);// 防止滑动的时候闪屏
        mUrl = AppContext.urlString;

        webview.loadUrl(mUrl);
        webview.reload();

        WebSettings webstting = webview.getSettings();
        webstting.setJavaScriptEnabled(true);
        webstting.setAllowFileAccess(true);
        webstting.setSupportZoom(true);
        webstting.setCacheMode(WebSettings.LOAD_DEFAULT);// 是否缓存
        webstting.setBlockNetworkImage(false);
        webstting.setJavaScriptCanOpenWindowsAutomatically(true);

        webstting.setDomStorageEnabled(true);
        webstting.setDatabaseEnabled(true);
        webstting.setDatabasePath(this.getApplicationContext().getCacheDir()
                .getAbsolutePath());
        // android 5.0以上默认不支持Mixed Content
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webstting.setMixedContentMode(
                    WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }

        /** 使webview自己处理打开网页事件，不调用系统浏览器打开 */
        // webview.setWebViewClient(new WebViewClient() {
        // @Override
        // public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // view.loadUrl(url);
        // return true;
        // }
        // // @Override
        // // public void onPageStarted(WebView view, String url, Bitmap
        // favicon) {
        // //
        // // LogUtils.d("webview", "开始加载url" + url);
        // //// showProgress();
        // //
        // // super.onPageStarted(view, url, favicon);
        // // }
        // //
        // // @Override
        // // public void onPageFinished(WebView view, String url) {
        // // LogUtils.d("webview", "加载完成url" + url);
        // //
        // //
        // //// stopProgress();
        // // super.onPageFinished(view, url);
        // // }
        // });
        setListener();
    }

    @Override
    protected void onPause() {
        _isVisible = false;

        super.onPause();
    }

    @Override
    protected void onResume() {
        _isVisible = true;
        super.onResume();
    }

    protected void showProgress() {
        if (_isVisible) {
            if (mProgress == null) {
                mProgress = new CallLogLoadingDialog(this, R.style.DialogLoadingTheme);
                mProgress.show();
                mProgress.settext(getString(R.string.loading));
            }
            if (mProgress != null) {
                mProgress.setCancelable(true);
                mProgress.setCanceledOnTouchOutside(false);
                mProgress.show();
            }
        }
    }

    /**
     * 停止进度条
     */
    protected void stopProgress() {
        if (_isVisible && mProgress != null) {
            try {
                mProgress.dismiss();
                mProgress = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    int ispingmu = 1;
    private boolean isjiazai = true;

    private void setListener() {
        Log.d("webview", "webview" + mUrl);

        webview.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // TODO Auto-generated method stub
                // handler.cancel();// Android默认的处理方式
                handler.proceed();// 接受所有网站的证书
                // handleMessage(Message msg);// 进行其他处理
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                LogUtils.d("webview", "开始加载url" + url);
                showProgress();
                if (url.equals(AppContext.indexUrl)) {
                    NewWebView.this.finish();

                    return;
                }
                if (url.equals(UrlTools.loginurl)) {
                    Intent intent = new Intent(UrlTools.loginurl);
                    NewWebView.this.sendBroadcast(intent);
                }
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                LogUtils.d("webview", "加载完成url" + url);

                AppContext.isFirst = true;
                webview.setVisibility(View.VISIBLE);
                stopProgress();
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.d("webview", "跳转：" + url);
                if (UrlManager.isWapLogin(url)) {// 跳转去登录
//					EventEngine.register(NewWebView.this);
                    Intent intent = new Intent(NewWebView.this,
                            BindActivity.class);
                    startActivity(intent);
                    return true;
                }
                if (url.contains("/wx_taskquery.action?m=query&id=")) {
                    Log.d("ceshiurl", "跳转之前：" + url);
                    String id = url.substring(
                            Tools.getCharacterPosition(url, "=", 2) + 1,
                            Tools.getCharacterPosition(url, "&", 2));
                    // Intent intent = new Intent(NewWebView.this,
                    // RelevantActivtiy.class);
                    // intent.putExtra("web", id);
                    // // intent.putExtra("web.url", UrlManager.getRootUrl()
                    // // + UrlTools.getObjectUrl(id));
                    // intent.putExtra("web.url", url);
                    // startActivity(intent);

                    Intent intent = new Intent(NewWebView.this,
                            BeauInfoActivity.class);
                    intent.putExtra("web", id);
                    if ((id.startsWith("bef")) || ((id.startsWith("bfa")))) {
                        intent.putExtra("web.url", UrlManager.getRootUrl()
                                + UrlTools.getObjectUrl_z(id));
                        intent.putExtra("from", "newwebview");
                    } else {
                        intent.putExtra("web.url", UrlManager.getRootUrl()
                                + UrlTools.getObjectUrl(id));
                    }
                    startActivity(intent);

                    // NewWebView.this.finish();
                    return true;
                } else if (url.contains("/weiquery.action?m=query&id=")) {
                    String id = url.substring(
                            Tools.getCharacterPosition(url, "=", 2) + 1,
                            url.length());
                    // Tools.i("followService", id);
                    // Intent intent = new Intent(NewWebView.this,
                    // RelevantActivtiy.class);
                    // intent.putExtra("web", id);
                    // intent.putExtra("web.url",
                    // UrlManager.APP_UR + UrlTools.getObjectUrl(id));
                    // startActivity(intent);

                    Intent intent = new Intent(NewWebView.this,
                            BeauInfoActivity.class);
                    intent.putExtra("web", id);
                    if ((id.startsWith("bef")) || ((id.startsWith("bfa")))) {
                        intent.putExtra("web.url", UrlManager.getRootUrl()
                                + UrlTools.getObjectUrl_z(id));
                    } else {
                        intent.putExtra("web.url", UrlManager.getRootUrl()
                                + UrlTools.getObjectUrl(id));
                    }
                    startActivity(intent);

                    return true;
                } else if (url.contains("/weiquery.action?id=")) {
                    String type = url.substring(
                            Tools.getCharacterPosition(url, "=", 2) + 1,
                            url.length());
                    Tools.i("followService", type);
                    if (type.equals("query")) {
                        String id = url.substring(
                                Tools.getCharacterPosition(url, "=", 1) + 1,
                                url.length() - 8);
                        Tools.i("followService", id);
                        Intent intent = new Intent(NewWebView.this,
                                RelevantActivtiy.class);
                        intent.putExtra("web", id);
                        intent.putExtra("web.url",
                                UrlManager.APP_UR + UrlTools.getObjectUrl(id));
                        startActivity(intent);
                        return true;
                    }

                } else if (url.contains("wx_taskquery.action?id=")) {
                    String id = url.substring(
                            Tools.getCharacterPosition(url, "=", 1) + 1,
                            Tools.getCharacterPosition(url, "&", 1));
                    Intent intent = new Intent(NewWebView.this,
                            BeauInfoActivity.class);
                    intent.putExtra("web", id);
                    if ((id.startsWith("bef")) || ((id.startsWith("bfa")))) {
                        intent.putExtra("web.url", UrlManager.getRootUrl()
                                + UrlTools.getObjectUrl_z(id));
                    } else {
                        intent.putExtra("web.url", UrlManager.getRootUrl()
                                + UrlTools.getObjectUrl(id));
                    }
                    startActivity(intent);
                    webview.stopLoading();
                    return true;
                }
//				else if(url.contains("weixinreportlist.action")) {
//					newurl = url;
//					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//
//				}
                else if (url.contains("weixinlistRunReport.action?reportId=") && isjiazai) {
                    Intent intent = new Intent(NewWebView.this, Newwebview1.class);
                    startActivity(intent);
                    AppContext.urlString = url;
//					newurl = url;
//                    //竖屏  SCREEN_ORIENTATION_PORTRAIT
//					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else {
                    newurl = url;
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }

                if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:") || url.startsWith("smsto:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if (url.contains("WeiXin_getUserTabList.action?appId")) {
                    finish();
                }

                if (UrlManager.isHome(url)) {
                    NewWebView.this.finish();
                    return true;
                } else {
                    // 自身加载新链接,不做外部跳转
                    view.loadUrl(url);
                    return true;
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                AppContext.isError = true;
                if ("en".equals(mEns)) {
                    view.loadUrl("file:///android_asset/html/en_error.html");
                } else {
                    view.loadUrl("file:///android_asset/html/error.html");
                }
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        if (!"".equals(newurl)) {
            webview.loadUrl(newurl);
//			if(newurl.contains("weixinlistRunReport.action?reportId=")){
//				isjiazai = false;
//				return;
//			}else if(newurl.contains("weixinreportlist.action")) {
//				isjiazai = true;
//			}

        }
//		  String message=newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE ? "屏幕设置为：横屏" : "屏幕设置为：竖屏";

//	         Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
}
